package com.msh.automatic.android.api;

import cn.hutool.core.io.FileUtil;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.jwk.RSAKey;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPublicKey;
import java.util.Base64;

@SpringBootTest
public class RASUtil {

    @Test
    public void generateKey() throws Exception {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(2048);
        KeyPair keyPair = keyGen.generateKeyPair();
        RSAKey rsaKey = new RSAKey.Builder((java.security.interfaces.RSAPublicKey) keyPair.getPublic())
                .privateKey(keyPair.getPrivate())
                .keyID("msh") // 给这个key一个唯一ID
                .build();
        String pem = convertToPEM(rsaKey.toRSAPublicKey());
        System.out.println(pem);
        String json = rsaKey.toJSONString();  // 包含私钥
        FileUtil.writeUtf8String(json,"C:\\Users\\fzh\\Desktop\\project\\msh\\automatic-android-api\\src\\main\\resources\\jwks.json");
    }
    private static String convertToPEM(RSAPublicKey publicKey) throws Exception {
        byte[] encoded = publicKey.getEncoded(); // X.509 encoded
        String base64Encoded = Base64.getMimeEncoder(64, new byte[]{'\n'}).encodeToString(encoded);
        return "-----BEGIN PUBLIC KEY-----\n" + base64Encoded + "\n-----END PUBLIC KEY-----";
    }

    // Nimbus 需要引入 Base64URL 类
    public static class Base64URL extends com.nimbusds.jose.util.Base64URL {
        public Base64URL(String value) {
            super(value);
        }
    }
}
